﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
using System.Web.Mvc;

namespace Rose.Models
{
public class ImageResizeResult : ActionResult
{
        private string _path;
        private int _width;
        private int _height;
        private bool _noZooming;

        public ImageResizeResult(string fileName, int width, int height, bool noZooming = false)
        {
           
            _path = HttpContext.Current.Server.MapPath(fileName);
           
            _width = width;
            _height = height;
            _noZooming = noZooming;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            byte[] buffer = new byte[4096];
            HttpResponseBase response = context.HttpContext.Response;

            //no context? stop processing
            if (context == null)
                throw new ArgumentNullException("context");

            //set files content type
            response.ContentType = "image/" + GetImageFormatFromFile().ToString();

            //get the resized image
            Image resizedImage = ResizeImage(_path);

            MemoryStream ms = new MemoryStream();
            resizedImage.Save(ms, GetImageFormatFromFile());
            MemoryStream imageStream = new MemoryStream(ms.ToArray());

            while (true)
            {
                int read = imageStream.Read(buffer, 0, buffer.Length);

                if (read == 0)
                    break;

                response.OutputStream.Write(buffer, 0, read);
            }
            response.End();

            ms.Dispose();
            imageStream.Dispose();
        }

        public Image ResizeImage(string imagePathToResize)
        {
            Image fullsizeImage;

            //check for file
            if (File.Exists(_path))
            {
                fullsizeImage = Image.FromFile(_path);
            }
            else
            {
                throw new FileNotFoundException(_path);
            }

            //load the images from the file system
            fullsizeImage = Image.FromFile(_path);

            // hack to prevent the internal thumbnail from being used!
            fullsizeImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
            fullsizeImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
            

            // can we zoom this image?
            if (_noZooming)
            {
                if (fullsizeImage.Width <= _width)
                {
                    _width = fullsizeImage.Width;
                }
            }

            // determine new height
            int newHeight = fullsizeImage.Height * _width / fullsizeImage.Width;
            if (newHeight > _height)
            {
                // Resize with height instead
                _width = fullsizeImage.Width * _height / fullsizeImage.Height;
                newHeight = _height;
            }
            
            Image newImage = fullsizeImage.GetThumbnailImage(_width, newHeight, null, IntPtr.Zero);
            
            //dispose of the in memory original
            fullsizeImage.Dispose();

            return newImage;
        }



        private ImageFormat GetImageFormatFromFile()
        {
            //get extension from path to determine contentType
            string[] parts = _path.Split('.');
            string extension = parts[parts.Length - 1];
            ImageFormat imageFormat;

            switch (extension.ToLower())
            {
                case "jpeg":
                case "jpg":
                    imageFormat = ImageFormat.Jpeg;
                    break;

                case "gif":
                    imageFormat = ImageFormat.Gif;
                    break;
                case "png":
                    imageFormat = ImageFormat.Png;
                    break;
                default:
                    throw new NotImplementedException(extension + " not handled");
            }
                
            return imageFormat;
        }
    
    }
}